package io.xxx.walle.wechaty;

import com.alibaba.fastjson2.JSON;
import io.xxx.walle.assistant.Token;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component
public class RobotClient {

    private final MediaType mediaType = MediaType.parse("application/json");

    private final OkHttpClient httpClient;
    @Value("${wechaty.robot.host:localhost}")
    private String host;
    @Value("${wechaty.robot.port:3000}")
    private Integer port;

    public RobotClient(OkHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    /**
     * 启动一个小助手
     */
    public Optional<String> create(Token token) throws IOException {
        HttpUrl url = new HttpUrl.Builder()
                .host(host)
                .port(port)
                .encodedPath("/assistant/create")
                .build();
        Map<String, Object> data = new HashMap<>() {{
            put("id", token.getId());
            put("value", token.getValue());
        }};
        RequestBody requestBody = RequestBody.create(JSON.toJSONString(data), mediaType);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try (Response response = httpClient.newCall(request).execute()) {
            ResponseBody body = response.body();
            if (body != null) {
                return Optional.of(body.string());
            }
        }
        return Optional.empty();
    }

    /**
     * 发送消息
     */
    public Optional<String> say(Message message) throws IOException {
        HttpUrl url = new HttpUrl.Builder()
                .host(host)
                .port(port)
                .encodedPath("/room/say")
                .build();
        RequestBody requestBody = RequestBody.create(JSON.toJSONString(message), mediaType);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try (Response response = httpClient.newCall(request).execute()) {
            ResponseBody body = response.body();
            if (body != null) {
                return Optional.of(body.string());
            }
        }
        return Optional.empty();
    }
}
